<script lang="ts" setup>
import { onMounted } from 'vue'
import * as monaco from 'monaco-editor'
import { EditorTheme } from '@/types/enum/configEnum'
import { EditorConfig} from '@/types/interfaces/configInterface'
import { useConfigStore } from '@/stores/useConfigStore'

const { setEditorConfig, getEditorConfig } = useConfigStore()

defineOptions({
  name: 'monaco-editor',
})
const props = defineProps({
  readOnly: {
    type: Boolean,
    default: false,
  },
})

let monacoEditor: monaco.editor.IStandaloneCodeEditor | null = null

const emit = defineEmits(['update:code', 'change'])

const initEditor = (id: string) => {
  const config = getEditorConfig() as EditorConfig
  if (document.getElementById(id) !== null) {
    monacoEditor = monaco.editor.create(document.getElementById(id), {
      ...config,
      readOnly: props.readOnly,
    })
  }
  // 监听编辑器内容变化,实现双向绑定
  monacoEditor?.onDidChangeModelContent(() => {
    const newCode = monacoEditor?.getValue()
    emit('update:code', newCode)
    emit('change', newCode)
  })
}

onMounted(() => {
  initEditor('monaco-editor')
})

// 暴露给父组件调用的方法
const setTheme = (theme: EditorTheme) => {
  monaco.editor.setTheme(theme)
  let config = getEditorConfig()
  config.theme = theme
  setEditorConfig(config)
}

const setFontSize = (fontSize: number) => {
  monacoEditor?.updateOptions({
    fontSize,
  })
  let config = getEditorConfig()
  config.fontSize = fontSize
  setEditorConfig(config)
}

const getEditorCode = () => {
  const code = monacoEditor?.getValue()
  return code || ''
}
const setEditorCode = (code: string) => {
  monacoEditor?.setValue(code)
}
const resizeEditor = () => {
  monacoEditor?.layout()
}
defineExpose({
  setTheme,
  setFontSize,
  getEditorCode,
  setEditorCode,
  resizeEditor,
})

// 双向绑定更新code的值
</script>

<template>
  <div id="monaco-editor"></div>
</template>

<style lang="scss" scoped>
#monaco-editor {
  width: 100%;
  height: 100%;
}
</style>
@/stores/useConfigStore
